package com.kaikai.edu.service.impl;

import com.kaikai.commonutils.JwtUtils;
import com.kaikai.commonutils.R;
import com.kaikai.edu.entity.EduUser;
import com.kaikai.edu.entity.ao.EduLoginAO;
import com.kaikai.edu.mapper.EduUserMapper;
import com.kaikai.edu.service.EduLoginService;
import com.kaikai.edu.service.EduUserService;
import com.kaikai.commonutils.BaseConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class EduLoginServiceImpl implements EduLoginService {

    @Autowired
    private EduUserMapper userMapper;

    @Autowired
    private EduUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public R login(EduLoginAO ao) {
        R result = R.ok();
        String accountName = ao.getAccountName();
        String password = ao.getPassword();
        if (StringUtils.isBlank(accountName) || StringUtils.isBlank(password)) {
            return R.error().message("用户名密码错误");
        }
        //查询账户是否被禁用
        EduUser user = userMapper.getUserByAccountName(accountName);
        if (user == null) {
            return R.error().message("用户名密码错误");
        }
        //判断是否禁用
        if (!BaseConstant.STATUS_IS_DISABLED.equals(user.getStatus())) {
            result = userService.loginAuth(ao);
        } else {
            return R.error().message("该账户已被禁用");
        }
        return result;
    }

        @Override
    public R logout(HttpServletRequest request) {
        try {
            String userId = JwtUtils.getMemberIdByJwtToken(request);
            String key = "token" + userId;
            Boolean hasToken = redisTemplate.hasKey(key);
            if(hasToken){
                redisTemplate.delete(key);
                return R.ok().message("退出登录成功");
            }else{
                return R.error().message("登录失效,请重新登陆");
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.error().message("退出异常");
        }

    }
}
